package com.china.produce.netty.learning.client.rpc;

import com.china.produce.netty.learning.message.rpc.RpcResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2024/9/21
 */
@ChannelHandler.Sharable
public class RpcResponseMessageHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {

    public static Map<Integer, Promise> promiseMap = new ConcurrentHashMap();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage msg) throws Exception {
        final Object returnValue = msg.getReturnValue();
        final Exception ex = msg.getExceptionValue();
        final Promise<Object> promise = promiseMap.remove(msg.getSequenceId());
        if (ex == null){
            promise.setSuccess(returnValue);
        }else{
            promise.setFailure(ex);
        }
    }
}
